package com.glxy.servlet;

import com.glxy.bean.Book;
import com.glxy.mapper.BookMapper;
import com.glxy.util.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import java.util.ArrayList;

public class BookServiceImpl implements BookService {

    @Override
    public ArrayList<Book> selectAll() {
        SqlSessionFactory sqlSessionFactory = MybatisUtils.getSqlSessionFactory();
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        BookMapper mapper = sqlSession.getMapper(BookMapper.class);
        ArrayList<Book> books = mapper.selectAll();
        return books;
    }

    @Override
    public ArrayList<Book> selectCondition(String queryName) {
        SqlSessionFactory sqlSessionFactory = MybatisUtils.getSqlSessionFactory();
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        BookMapper mapper = sqlSession.getMapper(BookMapper.class);
        ArrayList<Book> books = mapper.selectCondition(queryName);
        return books;
    }

    @Override
    public void addBook(Book book) {
        SqlSessionFactory sqlSessionFactory = MybatisUtils.getSqlSessionFactory();
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        BookMapper mapper = sqlSession.getMapper(BookMapper.class);
        mapper.addBook(book);
    }

    @Override
    public void delete(Integer id) {
        SqlSessionFactory sqlSessionFactory = MybatisUtils.getSqlSessionFactory();
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        BookMapper mapper = sqlSession.getMapper(BookMapper.class);
        mapper.deleteByID(id);
    }

    @Override
    public int update(Book book) {
        SqlSessionFactory sqlSessionFactory = MybatisUtils.getSqlSessionFactory();
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        BookMapper mapper = sqlSession.getMapper(BookMapper.class);
        int update = mapper.update(book);
        return update;
    }
}
